package src

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"math"
	"mime/multipart"
	"net/http"
	"path"
	"text/template"
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/sirupsen/logrus"
)

var tmplCard = `{
    "msgtype":"template_card",
    "template_card":{
        "card_type":"news_notice",
        "source":{
            "icon_url":"https://wework.qpic.cn/wwpic/252813_jOfDHtcISzuodLa_1629280209/0",
            "desc":"金融创新部"
        },
        "main_title":{
            "title":"{{ .RuleName }}",
            "desc":"{{ .Message }}"
        },
        "card_image":{
            "url":"{{ .ImageUrl }}",
            "aspect_ratio":2.25
        },
        "vertical_content_list":[
            {
                "title":"{{ .Title }}",
                "desc":"当前值: {{ (index .EvalMatches 0).value }}"
            }
        ],
        "horizontal_content_list":[
            {
                "keyname":"详细内容",
                "value":"下载",
                "type":{{ .Tags.contentType }},
                "media_id":"{{ .Tags.mediaID }}"
            }
        ],
        "jump_list":[
            {
                "type":1,
                "url":"{{ .RuleUrl }}",
                "title":"报警规则"
            }
        ],
        "card_action":{
            "type":1,
            "url":"{{ .ImageUrl }}",
            "appid":"APPID",
            "pagepath":"PAGEPATH"
        }
    }
}`

func hook2Card(h *Hook) (string, error) {
	tpl, err := template.New("wxchat").Parse(tmplCard)
	if err != nil {
		return "", err
	}
	buf := bytes.Buffer{}
	err = tpl.Execute(&buf, &h)
	if err != nil {
		return "", err
	}
	return buf.String(), nil
}

func upFile(botKey string, content []byte) (string, error) {
	upURL := fmt.Sprintf(`https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=%s&type=file`, botKey)
	c := http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		},
	}

	bodyBuf := &bytes.Buffer{}
	bodyWriter := multipart.NewWriter(bodyBuf)

	//关键的一步操作
	fileWriter, err := bodyWriter.CreateFormFile("uploadfile", "responsemsg")
	if err != nil {
		logrus.Error("error writing to buffer")
		return "", err
	}

	_, err = fileWriter.Write(content)
	if err != nil {
		logrus.Error("write error")
		return "", err
	}

	//添加其他参数
	//param := map[string]string{}
	//if len(param) != 0 {
	//	//param是一个一维的map结构
	//	for k, v := range param {
	//		bodyWriter.WriteField(k, v)
	//	}
	//}
	contentType := bodyWriter.FormDataContentType()
	bodyWriter.Close()

	resp, err := c.Post(upURL, contentType, bodyBuf)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	resp_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	mapResp := make(map[string]interface{})
	err = json.Unmarshal(resp_body, &mapResp)
	if err != nil {
		return "", err
	}
	if mapResp["errcode"].(float64) != 0 {
		return "", errors.New(mapResp["errmsg"].(string))
	}
	logrus.Info(resp.Status, ":", string(resp_body))
	return mapResp["media_id"].(string), nil
}

func SendCard(c *fiber.Ctx) error {
	botKey := c.Params("key")
	h := new(Hook)
	h.EvalMatches = make([]map[string]interface{}, 0)
	h.Tags = make(map[string]interface{})

	// h := make(map[string]interface{})
	logrus.Info(string(c.Body()))
	err := c.BodyParser(&h)
	if err != nil {
		c.SendString(err.Error())
		return err
	}

	// 数据清洗
	if h.ImageUrl == "" {
		h.ImageUrl = "https://wework.qpic.cn/wwpic/354393_4zpkKXd7SrGMvfg_1629280616/0"
	} else { // 只取文件名,将访问地址进行转换
		fileName := path.Base(h.ImageUrl)
		h.ImageUrl = "http://172.20.62.101:30003/webroot/png/" + fileName
	}
	if len(h.EvalMatches) == 0 {
		em := make(map[string]interface{})
		em["value"] = 0
		h.EvalMatches = append(h.EvalMatches, em)
	} else {
		for _, v := range h.EvalMatches { // 两位小数
			v["value"] = math.Round(v["value"].(float64)*100) / 100
		}
	}
	// 截图或附件上传
	mid, err := upFile(botKey, c.Body())
	if err != nil {
		h.Tags["contentType"] = 0
		h.Tags["mediaID"] = "无图片"
	} else {
		h.Tags["contentType"] = 2
		h.Tags["mediaID"] = mid
	}

	strMsg, err := hook2Card(h)
	if err != nil {
		return err
	}

	logrus.Info("send card: ", strMsg)
	return send(botKey, strMsg)

	// url := URL + botKey
	// logrus.Info(url)

	// jsonStr := []byte(strMsg)
	// req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	// if err != nil {
	// 	c.SendString(err.Error())
	// 	return err
	// }
	// req.Header.Set("Content-Type", "application/json")
	// client := &http.Client{
	// 	Timeout: 3 * time.Second,
	// }
	// resp, err := client.Do(req)
	// if err != nil {
	// 	c.SendString("Error sending to WeChat Work API " + err.Error())
	// 	return errors.New("error sending to WeChat Work API " + err.Error())
	// }
	// defer resp.Body.Close()
	// bs, _ := ioutil.ReadAll(resp.Body)

	// logrus.Info(string(bs))

	// err = c.SendString(string(bs))
	// if err != nil {
	// 	logrus.Error(err.Error())
	// }
	// return err
}
